//
//  CountryViewController.swift
//  
//
//  Created by CJX on 2016/10/25.
//
//

import UIKit
import SwiftyJSON
import SVProgressHUD

protocol CountryViewControllerDelegate {
    func giveTheCountryNameToUpDateVC(country:String,id:String)
}

class CountryViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var delegate : CountryViewControllerDelegate?
    
    
    var myTableView = UITableView(frame: CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64), style: .Plain)
    var dataDic = NSDictionary()
    
    var cartArr = NSArray()
    var dataArr = NSMutableArray()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.creatNavView()
        self.getData()
        self.creatTableView()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}


extension CountryViewController{
    private func creatNavView(){
        self.view.backgroundColor = UIColor.whiteColor()
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.title = "CHOOSE THE COUNTRY"
        
        let leftBtn = UIButton(type: .Custom)
        leftBtn.setImage(UIImage(named: "nav_back"), forState: .Normal)
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), forControlEvents: .TouchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    
}
extension CountryViewController{
    private func getData(){
        let parma = ["main_page":"countries"]
        
        NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: parma) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                let dic = ((result as! NSDictionary)["data"] as! NSDictionary)["countries"] as! NSDictionary
                self.dataDic = dic
                self.cartArr = dic.allKeys
                self.prepareData()
                self.myTableView.reloadData()
            }else{
                SVProgressHUD.showErrorWithStatus("get country data error:" + String(error))
                print("get country data error:" + String(error))
            }
        }
        
        
    }
    
    func prepareData(){
        
        let popularArr = ["United States","Puerto Rico","United Kingdom","Ireland","Australia","New Zealand","Canada","Germany","France","Italy","Spain","Philippines","Singapore"]
        let firstModel = NSMutableArray()
        for str in popularArr {
            firstModel.addObject(str)
        }
        let firstDic = NSMutableDictionary()
        firstDic.setObject("#", forKey: "Title")
        firstDic.setObject(firstModel, forKey: "Arr")
        
        dataArr.addObject(firstDic)
        
        
        for i in 65...90{
            let str1 = Character(UnicodeScalar(i))
            
            
            let cartMenuArr = NSMutableArray()
            for str in cartArr {
//                print((str as! NSString).substringToIndex(1))
//                print(str1)
//                print(String(str1))
                if (str as! NSString).substringToIndex(1) == String(str1){
                    cartMenuArr.addObject(str)
                }
                
                
            }
            
            let dic = NSMutableDictionary()
            dic.setObject( String(str1), forKey: "Title")
            dic.setObject(cartMenuArr, forKey: "Arr")
            
            dataArr.addObject(dic)
            
        }
    }
    
    
    
}

extension CountryViewController{
    private func creatTableView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return dataArr.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let dic = dataArr[section] as? NSDictionary
        let array = dic!["Arr"]as?NSArray
        return (array?.count)!
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }
        
        let dic = dataArr[indexPath.section] as? NSDictionary
        let array = dic!["Arr"]as?NSArray
        
        cell?.textLabel?.text = array![indexPath.row]as?String
        cell?.textLabel?.textColor = UIColor.grayColor()
        cell?.selectionStyle = .None
        return cell!
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "Popular Countries"
            
        }
        let dic = dataArr[section] as? NSDictionary
        return dic!["Title"] as? String
        
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let dic = dataArr[indexPath.section] as? NSDictionary
        let array = dic!["Arr"]as?NSArray
        let countryStr = array![indexPath.row] as? String
        let idStr = self.dataDic[countryStr!] as? String
        print(countryStr!)
        print(idStr!)
        
        self.delegate?.giveTheCountryNameToUpDateVC(countryStr!, id: idStr!)
        
        self.navigationController?.popViewControllerAnimated(true)
    }
    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        tableView.sectionIndexColor = UIColor.blueColor()
        let arr = NSMutableArray()
        for dic in dataArr {
            arr.addObject((dic["Title"]as?String)!)
        }
        return arr as? [String]
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SCREEN_HEIGHT * 0.05
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return SCREEN_HEIGHT * 0.06
    }
}















